package com.domel76.quickfilm.dao;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.domel76.quickfilm.beans.CinemaBean;
import com.domel76.quickfilm.beans.FilmBean;
import com.domel76.quickfilm.common.Constans;

public class CommonDAO {

	public SQLiteDatabase baza;

	public CommonDAO() {

	}

	public CommonDAO(Activity a) {
		baza = a.openOrCreateDatabase(Constans.DB_NAME, Context.MODE_PRIVATE, null);
	}

	public CommonDAO(SQLiteDatabase baza) {
		this.baza = baza;
	}

	public int getIdFilmByTitle(String title) {
		Cursor cursor = baza.rawQuery("SELECT id FROM " + Constans.TABLE_FILM + " where title = '" + title.replaceAll("'", "") + "'", null);

		if (cursor.moveToFirst()) {
			return cursor.getInt(cursor.getColumnIndex("id"));
		}
		return -1;
	}

	public int getIdFilmByTitleAndInsert(FilmBean film) {
		int id = getIdFilmByTitle(film.title);
		if (id > 0) {
			return id;
		} else {
			// Insert New Film
			baza.execSQL("INSERT INTO " + Constans.TABLE_FILM + " (title,description,runtime, details, link, rating, country, release, genre, linkImage) values" + " ('"
					+ film.title.replaceAll("'", "") + "','" + film.description + "','" + film.runtime + "','" + film.all + "','"
					+ film.link + "','" + film.rating + "','" + film.country + "','" + film.release + "','" + film.genre + "','" + film.linkImage + "');");
			return getIdFilmByTitle(film.title);
		}
	}

	public int getIdCinemaByName(String name) {
		Cursor cursor = baza.rawQuery("SELECT id FROM " + Constans.TABLE_CINEMA + " where name = '" + name.replaceAll("'", "") + "'", null);

		if (cursor.moveToFirst()) {
			return cursor.getInt(cursor.getColumnIndex("id"));
		}
		return -1;
	}

	public int getIdCinemaByTitleAndInsert(CinemaBean cinema) {
		int id = getIdCinemaByName(cinema.name);
		if (id > 0) {
			return id;
		} else {
			// Insert New Film
			baza.execSQL("INSERT INTO " + Constans.TABLE_CINEMA + " (name, address) values ('" + cinema.name.replaceAll("'", "") + "','');");
			return getIdCinemaByName(cinema.name);
		}
	}

	public void insertHour(int filmId, int cinemaId, String hour) {
		baza.execSQL("INSERT INTO " + Constans.TABLE_SEANS + " (film_id, cinema_id, hour) values (" + filmId + "," + cinemaId + ",'" + hour + "');");
	}
}
